import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Button} from '@tarojs/components'
import {http} from '../../../utils/http'
import {CREATE_SITE_POSTER_INFO, RESOURCE_URL} from '../../../constants/api'
import {platform} from '../../../utils/platform-settting.service'
import {user} from '../../../utils/user.service'
import {PlatformSet} from '../../../utils/server.interface'
import {getPoster} from "../../../utils/poster.service";
import {vcmonitor} from "../../../utils/tools";
import {h5Wx} from "../../../utils/h5.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import './invite.scss'

export default class Invite extends Component {
  state: {
    showPoster: boolean
    sellerId: number
    sourceUserId: number
    sid: number
    platformName: string
    shareoff: boolean
    setting: PlatformSet
  } = {
    showPoster: false,
    sellerId: 0,
    sourceUserId: 0,
    sid: 0,
    platformName: '',
    shareoff: false,
    setting: {
      platformName: '',
      platformServicePhone: '',
      sellerRegType: 0,
      platformSellerType: 0,
      isShowServicePhone: 0
    }
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      const {sellerId = '', sid = '', sourceUserId = '' } = Taro.getCurrentInstance().router.params
      const setting = await platform.getSetting()
      const timestamp = new Date().getTime()
      await h5Wx.getConfig()
      let url = '';
      if (setting && (setting.sellerRegType == 2 || setting.sellerRegType == 3)) {
        url = `/common/distributor/invite/register?sid=${sid}&sourceUserId=${sourceUserId}&timestamp=${timestamp}`;
      } else {
        url = `/common/distributor/invite/join?sid=${sid}&sourceUserId=${sourceUserId}&timestamp=${timestamp}`;
      }

      if (sellerId) {
        url += `&sellerId=${sellerId}`
      }
      const shareData = {
        title: platform.info.platformName,
        desc: '点击申请成为' + process.env.fxName,
        link: window.location.origin + url,
        imgUrl: RESOURCE_URL + '/resources/system/img/joinus.jpg'
      }
      h5Wx.share(shareData)
    }
  }

  async componentDidShow() {
    Taro.setNavigationBarTitle({
      title: '发展' + process.env.fxName
    })
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({title: '登录已失效'})
      user.jumpLogin()
      return
    }
    const {sellerId = '', sid = '', sourceUserId = ''} = Taro.getCurrentInstance().router.params
    const showPoster = !!sellerId
    const setting = await platform.getServerSet()
    if (setting) {
      this.setState({sellerId, sid, sourceUserId, showPoster, platformName: setting.platformName, setting})
    } else {
      this.setState({sellerId, sid, sourceUserId, showPoster})
    }

  }

  onShareAppMessage(res) {
    const {sellerId, sid, sourceUserId, setting} = this.state
    const timestamp = new Date().getTime()
    let url = '';
    if (setting && (setting.sellerRegType == 2 || setting.sellerRegType == 3)) {
      url = `/common/distributor/invite/register?sid=${sid}&sourceUserId=${sourceUserId}&timestamp=${timestamp}`;
    } else {
      url = `/common/distributor/invite/join?sid=${sid}&sourceUserId=${sourceUserId}&timestamp=${timestamp}`;
    }

    if (sellerId) {
      url += `&sellerId=${sellerId}`
    }
    return {
      title: '点击申请成为' + process.env.fxName,
      path: url + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
      imageUrl: RESOURCE_URL + '/resources/system/img/joinus.jpg'
    }
  }

  async getPoster() {
    Taro.showLoading({title: '加载中...'})
    const showPoster = this.state.showPoster
    if (showPoster) {
      const poster = await getPoster('distributor', '', !this.state.sellerId ? 'site' : '')
      if (poster) {
        if (process.env.TARO_ENV === "h5") {
          Taro.navigateTo({
            url: '/distributor/poster/poster?url=' + poster.url
          })
        } else {
          try {
            const ret = await Taro.getImageInfo({src: poster.url})
            Taro.hideLoading()
            if (ret) {
              Taro.navigateTo({
                url: '/distributor/poster/poster?url=' + ret.path
              })
            }
          } catch (e) {
            Taro.showToast({title: '获取海报失败', icon: 'none'})
          }
        }

      } else {
        Taro.hideLoading()
      }
    } else {
      Taro.hideLoading()
      this.siteInvitePoster()
    }
  }

  async siteInvitePoster() {
    const ret = await http.HGet(CREATE_SITE_POSTER_INFO, {})
    if (ret.type === 0) {
      if (process.env.TARO_ENV === "h5") {
        Taro.navigateTo({
          url: '/distributor/poster/poster?url=' + ret.url
        })
      } else {
        try {
          const res = await Taro.getImageInfo({src: ret.url})
          if (res) {
            Taro.navigateTo({
              url: '/distributor/poster/poster?url=' + res.path
            })
          }
        } catch (e) {
          //console.log(e)
        }
      }
    } else if (ret.type === 1) {
      const poster = await getPoster('distributor', '', !this.state.sellerId ? 'site' : '')
      //const res = await http.get<string>(GET_DISTRIBUTOR_INFO, {})
      if (poster) {
        if (process.env.TARO_ENV === "h5") {
          Taro.navigateTo({
            url: '/distributor/poster/poster?url=' + poster.url
          })
        } else {
          try {
            const result = await Taro.getImageInfo({src: poster.url})
            Taro.hideLoading()
            if (result) {
              Taro.navigateTo({
                url: '/distributor/poster/poster?url=' + result.path
              })
            }
          } catch (e) {
            Taro.showToast({title: '获取海报失败', icon: 'none'})
          }
        }

      } else {
        Taro.hideLoading()
      }
    }
  }

  render() {
    const {platformName, shareoff} = this.state
    return (
      <View className='invite-root'>
        <GzhAuth/>
        <View className='wrap'>
          <View className='header'>
            <View className='text' decode><View>【{platformName}】</View><View>邀请您加入我们的营销团队</View></View>
          </View>
          <View className='content'>
            <View className='title'>操作步骤：</View>
            <View style='height: 1Px; background:#efefef; margin: 15px 0;'></View>
            <View className='tips'>1、点击下方按钮</View>
            <View className='tips'>2、选择微信朋友后发送</View>
            <View className='tips'>3、朋友点击分享内容填写信息即可注册</View>
          </View>
        </View>
        <View className='btn-box'>
          {/* <View className="button invite">分享链接,邀请好友</View> */}
          {process.env.TARO_ENV === 'weapp' && <Button className='button invite' openType='share'>分享链接，邀请好友</Button>}
          {process.env.TARO_ENV === 'h5' && <Button className='button invite' openType='share' onClick={() => {
            this.setState({shareoff: true})
          }}
          >分享链接，邀请好友</Button>}
          <View className='button share' onClick={this.getPoster.bind(this)}>分享海报</View>
        </View>
        {shareoff && <View className='H5shareBox' onClick={() => {
          this.setState({shareoff: false})
        }}
        >
          <Image className='H5shareImg' src='https://resource.ivcheng.com/resources/images/H5sharebj.png'
                 mode='widthFix'
          ></Image>
          <View className='H5shareBtn'>我知道了</View>
        </View>
        }
      </View>
    )
  }
}
